<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert show-icon title="注意：只能选择三级分类参数！" type="warning" :closable="false"></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader :options="catelist" :props="cateProps"  @change=" handleChange" v-model="selectedCatekeys" clearable  ></el-cascader>
        </el-col>
      </el-row>
      <!--页签部分-->
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button size="mini" type="primary" @click="addDialogVisible = true" :disabled="isBtnDisabled">添加参数</el-button>
          <!--表格-->
          <el-table :data="manyTableData" style="width: 100%" border>
            <!--展开行-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope.row)" closable>{{item}}</el-tag>
                <el-input class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" ></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit"  @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParamsById(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button size="mini" type="primary" @click="addDialogVisible = true" :disabled="isBtnDisabled">添加属性</el-button>
          <el-table :data="onlyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope.row)" closable>{{item}}</el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit"  @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParamsById(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--添加参数对话框-->
    <el-dialog  :title=" '添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
    </el-dialog>
    <!--添加参数对话框-->
    <el-dialog  :title=" '修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
    </el-dialog>

  </div>

</template>

<script>
    export default {
      data() {
        return {
          catelist: [],
          cateProps: {
            value: 'cat_id',
            label: 'cat_name',
            children: 'children'
          },
          selectedCatekeys: [],
          activeName: 'many',
          manyTableData: [],
          onlyTableData: [],
          addDialogVisible: false,
          addForm: {
            attr_name: ''
          },
          // 添加验证规则
          addFormRules: {
            attr_name: [
              {required: true, message: '请输入参数', trigger: 'blur'}
            ]
          },
          editDialogVisible: false,
          editForm: {},
          // 修改验证规则
          editFormRules: {
            attr_name: [
              {required: true, message: '请输入参数', trigger: 'blur'}
            ]
          }
        }
      },
      created() {
        this.getCateList();
      },
      methods: {
        async getCateList() {
          const {data: res} = await this.$http.get('categories');
          if (res.meta.status !== 200) return this.$message.error({message: '获取分类列表失败！'});
          this.catelist = res.data
        },
        // 选中父级分类触发函数
        handleChange() {
         this.getParamsData()
        },
        handleTabClick() {
          console.log(this.activeName);
          this.getParamsData()
        },
        // 获取参数列表数据
        async getParamsData() {
          // 如果不是三级分类就清空数组
          if (this.selectedCatekeys.length !== 3) {
            this.selectedCatekeys = [];
            this.manyTableData = [];
            this.onlyTableData = []
            return
          }
          console.log(this.selectedCatekeys);
          // 根据所选三级分类ID查询对应参数
          const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {
              sel: this.activeName
            }});
          if (res.meta.status !== 200) return this.$message.error({message: '获取参数列表失败！'});
          console.log(res);
          // 将attr_vals转为数组
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
            // 控制文本框显示隐藏
            item.inputVisible = false;
            // 文本框输入的值
            item.inputValue = ''
          })
          if (this.activeName === 'many') {
            this.manyTableData = res.data
          } else {
            this.onlyTableData = res.data
          }
        },
        // 监听关闭添加对话框
        addDialogClose() {
          this.$refs.addFormRef.resetFields();
        },
        // 添加参数
        addParams() {
          this.$refs.addFormRef.validate(async valid => {
            if (!valid) return; // 判断校验是否通过
            const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            });
            if (res.meta.status !== 201) return this.$message.error({message: '添加参数失败！'});
            this.$message.success({message: '添加参数成功！'});
            this.addDialogVisible = false;
            this.getParamsData();
          })
        },
        async showEditDialog(attr_id) {
          const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
            params: {attr_sel: this.activeName}
          });
          if (res.meta.status !== 200) return this.$message.error({message: '获取参数失败！'});
          this.editForm = res.data;
          this.editDialogVisible = true
        },
        // 监听关闭修改对话框
        editDialogClose() {
          this.$refs.editFormRef.resetFields();
        },
        // 修改
        editParams() {
          this.$refs.editFormRef.validate(async valid => {
            if (!valid) return; // 判断校验是否通过
            const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName
            });
            if (res.meta.status !== 200) return this.$message.error({message: '修改参数失败！'});
            this.$message.success({message: '修改参数成功！'});
            this.getParamsData();
            this.editDialogVisible = false
          })
        },
        // 删除
        async removeParamsById(id) {
          const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err);
          // 确定返回字符串 confirm ，取消返回字符串 cancel
          if (confirmResult === 'cancel') {
            return this.$message.info('已经取消删除！');
          }
          console.log('确定删除')
          const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`);
          if (res.meta.status !== 200) return this.$message.error({message: '删除参数失败！'});
          this.$message.success({message: '删除参数成功！'});
          this.getParamsData();
        },
        // 文本框失去焦点触发
        handleInputConfirm(row) {
          if (row.inputValue.trim().length === 0) {
            row.inputVisible = false;
            row.inputValue = '';
            return
          }
          // 后续处理
          row.attr_vals.push(row.inputValue.trim());
          row.inputValue = '';
          row.inputVisible = false;
          // 保存这次操作
          this.saveAttrVals(row)
        },
        showInput(row) {
          row.inputVisible = true;
          // 让文本框自动获取焦点
          // $nextTick 方法的作用当页面上元素重新渲染之后，才会指定回调函数代码
          this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
          });
        },
        // 对attr_vals保存数据库
        async saveAttrVals(row) {
          // 保存参数
          const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(',')
          });
          if (res.meta.status !== 200) return this.$message.error({message: '操作失败！'});
          this.$message.success({message: '操作成功！'});
        },
        handleClose(i, row) {
          row.attr_vals.splice(i, 1);
          this.saveAttrVals(row)
        }

      },
      computed: {
        // 控制按钮的是否禁用
        isBtnDisabled() {
          if (this.selectedCatekeys.length !== 3) {
            return true
          }
          return false
        },
        // 选择的
        cateId() {
          if (this.selectedCatekeys.length === 3) {
            return this.selectedCatekeys[2]
          }
          return null
        },
        titleText() {
          if (this.activeName === 'many') {
            return '动态参数'
          }
          return '静态参数'
        }

      }

    }
</script>

<style lang="less" scoped>
  .cat_opt{
    margin: 15px 0;
  }
  .el-button{
    margin-bottom: 15px;
  }
  .el-tag{
    margin: 5px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
